package com.ieng.ormosia.web.controller.common;

import com.ieng.ormosia.common.utils.ActionR;
import com.ieng.ormosia.common.utils.RsaUtils;
import com.ieng.ormosia.common.vo.ResponseData;
import com.ieng.ormosia.web.action.LoginAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AuthorizationController {
    @Autowired
    private AuthenticationManagerBuilder authenticationManagerBuilder;

    @PostMapping("/sign-in")
    public ResponseData doLogin(@Validated @RequestBody LoginAction loginAction) throws Exception {
        String password = RsaUtils.decryptByPrivateKey("", loginAction.getPassword());
        //验证码验证
        //...

        //Security 用户登录
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginAction.getUsername(), password);
        Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //生成Token
        //...

        return ActionR.success(null);
    }

    @GetMapping("/captcha")
    public ResponseData captcha(){
        //生成base64验证码
        //...
        return ActionR.success(null);
    }

    @GetMapping("/logout")
    public ResponseData logout(){
        //退出登录
        //...
        return ActionR.send("退出成功");
    }

}
